import 'package:eplorex/models/message/message.dart';
import 'package:eplorex/models/message/message_content.dart';
import 'package:eplorex/providers/local_db.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:eplorex/models/message/chat_message_type.dart' as types;
import 'package:uuid/uuid.dart';


class ChatAddView extends StatefulWidget {

  //刷新列表
  final refreshMediaCallback;

  //发送信息
  final sendMedialCallback;

  //聊天id
  final String toChatId;

  //刷新红包、转账
  final refreshRedpacketAndTransfer;

  //1单聊， 2群聊
  final int viewType;

  ChatAddView(
      {required this.viewType, required this.toChatId, required this.refreshMediaCallback, required this.sendMedialCallback, required this.refreshRedpacketAndTransfer});

  @override
  State<StatefulWidget> createState() => _ChatAddState();

}

class _ChatAddState extends State<ChatAddView> {

  @override
  Widget build(BuildContext context) {
    return getAddWidget();
  }

  //相册
  List ablums = ["assets/add_gallary.png", "assets/add_gallary.png"];
  int ablumsPosition = 0;

  //拍照
  List takePhotos = ["assets/add_ camara.png", "assets/add_ camara.png"];
  int takePhotosPosition = 0;

  //视频通话
  List videoCalls = ["assets/add_ location.png", "assets/add_ location.png"];
  int videoCallsPosition = 0;


  //相册
  final TYPE_ABLUM = 1;

  //拍照
  final TYPE_TAKE_PHOTO = 2;

  //视频通话
  final TYPE_VIDEO_CALL = 3;

  //语音通话
  final TYPE_VOICE_CALL = 4;

  //红包
  final TYPE_RED_PACKET = 5;

  //转账
  final TYPE_TRANSFER = 6;

  final _user = const types.User(
    uid: '4c2307ba-3d40-442f-b1ff-b271f63904ca',
  );


  //改变状态
  void _changeStatus(int type, int position) {
    if (type == TYPE_ABLUM) {
      ablumsPosition = position;
      ablums[ablumsPosition];
    } else if (type == TYPE_TAKE_PHOTO) {
      takePhotosPosition = position;
      takePhotos[takePhotosPosition];
    } else if (type == TYPE_VIDEO_CALL) {
      videoCallsPosition = position;
      videoCalls[videoCallsPosition];
    }
    setState(() {});
  }

  Widget getAddWidget() {
    return Container(
      //margin: EdgeInsets.only(top: 40, bottom: AppManager.getInstance().getBottom(context) + 20),
      alignment: Alignment.center,
      child: Center(
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              //交叉轴的布局方式，对于column来说就是水平方向的布局方式
              crossAxisAlignment: CrossAxisAlignment.center,
              //就是字child的垂直布局方向，向上还是向下
              verticalDirection: VerticalDirection.down,
              children: [
                _buildBottomItem(TYPE_ABLUM),
                _buildBottomItem(TYPE_TAKE_PHOTO),
                Offstage(
                  offstage: widget.viewType == 2,
                  child: _buildBottomItem(TYPE_VIDEO_CALL),
                ),
                Offstage(
                  offstage: widget.viewType == 2,
                  child: _buildBottomItem(TYPE_VOICE_CALL),
                ),

              ],
            ),

            Offstage(
              offstage: widget.viewType == 2,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                //交叉轴的布局方式，对于column来说就是水平方向的布局方式
                crossAxisAlignment: CrossAxisAlignment.center,
                //就是字child的垂直布局方向，向上还是向下
                verticalDirection: VerticalDirection.down,
                children: [
                  _buildBottomItem(TYPE_RED_PACKET),
                  _buildBottomItem(TYPE_TRANSFER),
                  _buildBottomItem(-1),
                  _buildBottomItem(-1),
                ],
              ),
            ),


          ],
        ),
      ),
    );
  }


  void _handleImageSelection() async {
    final result = await ImagePicker().pickImage(
      imageQuality: 70,
      maxWidth: 1440,
      source: ImageSource.gallery,
    );

    if (result != null) {
      final bytes = await result.readAsBytes();
      final image = await decodeImageFromList(bytes);

      final message = types.ImageMessage(
        author: _user,
        createdAt: DateTime
            .now()
            .millisecondsSinceEpoch,
        height: image.height.toDouble(),
        id: const Uuid().v4(),
        name: result.name,
        size: bytes.length,
        uri: result.path,
        width: image.width.toDouble(),
        messageContent: ImageMessageContent.fromParams(result.name
            , image.width.toDouble(), image.height.toDouble()
            ,  bytes.length,  result.path)
      );

      _addMessage(message);
    }
  }

  void _addMessage(types.Message message) {
    DatabaseHelper.instance.insertMessage({
      "createdAt": DateTime
          .now()
          .millisecondsSinceEpoch,
      "senderId": "_user.uid",
      "receiverId": "e52552f4-835d-4dbe-ba77-b076e659774d",
      "status": message.status ?? Status.sending.name,
      "content": "content wait to be fixed.",
      "type": message.type.name
    });
    widget.sendMedialCallback(1, "mediaURL", "messageId");
  }

  Widget _buildBottomItem(int type) {
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.only(top: 10, bottom: 10),
      child: GestureDetector(
        child: _getBottomWidget(type),
        onTap: () {
          _changeStatus(type, 0);
          if (type == TYPE_ABLUM) {
            _openAblumPermission();
          }
        },
        onTapCancel: () {
          _changeStatus(type, 0);
        },
        onTapDown: (data) {
          _changeStatus(type, 1);
        },
      ),
    );
  }


  Widget _getBottomWidget(int type) {
    Decoration decoration= BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(10.0));
    if (type == TYPE_ABLUM) {
      return Column(
        children: [
          Container(
            decoration: decoration,
            child: Image.asset(ablums[ablumsPosition], width: 50, height: 50,),
          ),
          const Text("相册"),
        ],
      );
    } else if (type == TYPE_TAKE_PHOTO) {
      return Column(
        children: [
          Container(
              decoration: decoration,
              child: Image.asset(
                takePhotos[takePhotosPosition], width: 50, height: 50,),
          ),
          const Text("拍照"),
        ],
      );
    } else if (type == TYPE_VIDEO_CALL) {
      return Column(
        children: [
          Container(
            decoration: decoration,
            child: Image.asset(
            videoCalls[videoCallsPosition], width: 50, height: 50,),)
          ,
          const Text("视频通话"),
        ],
      );
    } else {
      //空白占位符
      return Column(
        children: [
          Container(
            width: 50,
            height: 50,
          ),
          Text(""),
        ],
      );
    }
  }

  //打开相册权限
  void _openAblumPermission() async {
    bool isPhotosGranted = await Permission.photos.isGranted;
    bool isPhotosDenied = await Permission.photos.isDenied;
    if (isPhotosGranted) {
      _handleImageSelection();
    } else {
      if (isPhotosDenied) {
        _handleImageSelection();
      } else {
        //跳转到设置页面提示
        // _showPhotosConfirmationAlert(context);
      }
    }
  }


}